//
//  CommonTools.swift
//  SDKDebuggingDemo
//
//  Created by 秦晟哲 on 2019/9/4.
//  Copyright © 2019 QinszQSZ. All rights reserved.
//

import Foundation
import CoreLocation

func ReqContent(title:String,task:KCTOldBLETaskBase) -> String{
    var content = "[\(title)]\n\n"
    
    let params = "\(task.yy_modelToJSONObject() ?? "KCTOldBLETaskBase转JSON失败")"
    
    content.append(params)
    
    return content
}

func ReqContent(title:String,content:String) -> String {
    var total = "[\(title)]\n\n"
    
    total.append(content)
    
    return total
}

func ResultContent(title:String,error:KCTError?,rspDes:String?) -> String {
    var content = "[\(title)]\n\n"
    
    content.append("errorInfo:\n")
    if let err = error{
        content.append(err.description)
    }else{
        content.append("无")
    }
    content.append("\n\n")
    
    content.append("result:\n")
    if let des = rspDes {
        content.append(des)
    }
    
    return content
}


func SplitData(data:Data,upperlimit:Int) -> Array<Data> {
    if upperlimit <= 0{
        return [data]
    }else{
        var dataArray = Array<Data>.init()
        var restData = data
        while restData.count > upperlimit {
            let range = Range.init(NSMakeRange(0, upperlimit))!
            let sliceData = restData.subdata(in: range)
            dataArray.append(sliceData)
            let restRange = Range.init(NSMakeRange(sliceData.count, restData.count - sliceData.count))!
            restData = restData.subdata(in: restRange)
        }
        
        dataArray.append(restData)
        
        return dataArray
    }
}


//将十六进制字符串转化为 Data
func HexToData(hexStr: String) -> Data? {
    if let bytes = Bytes(from: hexStr){
        return Data(bytes: bytes)
    }else{
        return nil
    }
}

// 将16进制字符串转化为 [UInt8]
// 使用的时候直接初始化出 Data
// Data(bytes: Array<UInt8>)
func Bytes(from hexStr: String) -> [UInt8]? {
    
    if hexStr.count % 2 != 0 {
        IPrint("String转[UInt8]错误:输入字符串个数为奇数")
        return nil
    }
    var bytes = [UInt8]()
    var sum = 0
    // 整形的 utf8 编码范围
    let intRange = 48...57
    // 小写 a~f 的 utf8 的编码范围
    let lowercaseRange = 97...102
    // 大写 A~F 的 utf8 的编码范围
    let uppercasedRange = 65...70
    for (index, c) in hexStr.utf8CString.enumerated() {
        var intC = Int(c.byteSwapped)
        if intC == 0 {
            break
        } else if intRange.contains(intC) {
            intC -= 48
        } else if lowercaseRange.contains(intC) {
            intC -= 87
        } else if uppercasedRange.contains(intC) {
            intC -= 55
        } else {
            IPrint("String转[UInt8]错误,存在非法字符:'\(c)'")
            return nil
        }
        sum = sum * 16 + intC
        // 每两个十六进制字母代表8位，即一个字节
        if index % 2 != 0 {
            bytes.append(UInt8(sum))
            sum = 0
        }
    }
    return bytes
}


func DFUMacString(macString:String) -> String? {
    
    var ary = macString.components(separatedBy: ":")
    
    if ary.count > 0{
        let lastValue = HexStringToInt(from: ary.last!)
        
        var targetValue = 0
        if lastValue == 0xff {
            targetValue = 0
        }else{
            targetValue = lastValue + 1
        }
        
        let targetStr = String.init(format: "%.2x", targetValue)
        
        ary.replaceSubrange(Range.init(NSMakeRange(ary.count - 1, 1))!, with: [targetStr])
        
        var macStr = ""
        for i in 0 ..< ary.count {
            if i == 0{
                macStr.append(ary[i])
            }else{
                macStr.append(":"+ary[i])
            }
        }
        return macStr
        
    }else{
        return nil
    }
}

func HexStringToInt(from:String) -> Int {
    let str = from.uppercased()
    var sum = 0
    for i in str.utf8 {
        sum = sum * 16 + Int(i) - 48 // 0-9 从48开始
        if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
            sum -= 7
        }
    }
    return sum
}


// MARK: - 打印CLLocation
extension CLLocation{
    open override var description: String {
        
        let formate = DateFormatter.init()
        formate.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateString = formate.string(from: self.timestamp)
        
        let dic : [String:Any] = ["timestamp":self.timestamp.timeIntervalSince1970,"localDateString":dateString,"latitude":self.coordinate.latitude,"longitude":self.coordinate.longitude,"altitude":self.altitude]
        
        let content = "\(dic)"
        return content
    }
}
